package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/uploadController")
public class UploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public void doUpload(MultipartFile[] files, HttpServletRequest request) throws IOException {
        for (MultipartFile multipartFile : files) {
            if(!multipartFile.isEmpty()){
                //获取文件上传的目录
                String realPath = request.getServletContext().getRealPath("/upload");
                //生成唯一的文件名
                String fileName=multipartFile.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                String uuid = UUID.randomUUID().toString().replace("-", "");
                fileName=uuid+suffix;
                multipartFile.transferTo(new File(realPath,fileName));
            }
        }
    }
}
